package com.woniuxy.joylife.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.woniuxy.common.utils.JWTUtils;
import com.woniuxy.joylife.gateway.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 登录验证，过滤
 */
@Component
@Configuration
public class loginFilter implements GlobalFilter, Ordered {
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取uri
        String uri = request.getPath().toString();
        //全部放行
//        if (uri.startsWith("/")) {
//            System.out.println("全部放行");
//            return chain.filter(exchange);
//        }
        System.out.println("请求地址："+uri);
        //验证登录页面放行
        if (uri.startsWith("/auth")) {
            System.out.println("登录请求，拦截器放行");
            return chain.filter(exchange);
        }
        //物业放行
        if (uri.startsWith("/manager")||uri.startsWith("/api")) {
            System.out.println("物业模块，拦截器放行");
            return chain.filter(exchange);
        }
        //社区图片
        /*if (uri.startsWith("/forum/img/joylife")) {
            System.out.println("社区图片请求，拦截器放行");
            return chain.filter(exchange);
        }*/
        //商店图片
        /*if (uri.startsWith("/shop/img/joylife")) {
            System.out.println("商店图片请求，拦截器放行");
            return chain.filter(exchange);
        }*/
        //聊天临时放行
        if (uri.startsWith("/forum/userChat")) {
            System.out.println("聊天临时放行");
            return chain.filter(exchange);
        }

        //后台临时放行
        if (uri.startsWith("/center")) {
            System.out.println("后台临时放行");
            return chain.filter(exchange);
        }



//        //后台静态资源临时放行
        if (uri.endsWith(".js")||uri.endsWith(".css")||uri.endsWith(".jpg")||uri.endsWith(".png")||uri.endsWith(".ico")||uri.endsWith(".gif")) {
            System.out.println("后台临时放行");
            return chain.filter(exchange);
        }
        //后台静态资源临时放行
        if (uri.startsWith("/center/lib")) {
            System.out.println("后台临时放行");
            return chain.filter(exchange);
        }

        //后台静态资源临时放行
        if (uri.startsWith("/center/api")) {
            System.out.println("后台临时放行");
            return chain.filter(exchange);
        }

//        if (uri.startsWith("/center/css")) {
//            System.out.println("后台临时放行");
//            return chain.filter(exchange);
//        }
//
//        if (uri.startsWith("/center/api")) {
//            System.out.println("后台临时放行");
//            return chain.filter(exchange);
//        }
//        if (uri.startsWith("/center/images")) {
//            System.out.println("后台临时放行");
//            return chain.filter(exchange);
//        }

        //注册时，加载社区
        if (uri.startsWith("/forum/allForum")) {
            System.out.println("注册请求社区，拦截器放行");
            return chain.filter(exchange);
        }
        //二手图片
        if (uri.startsWith("/market/img/joylife")) {
            System.out.println("二手图片请求，拦截器放行");
            return chain.filter(exchange);
        }
        //注册时，提交图片
        if (uri.startsWith("/forum/addImg")) {
            System.out.println("上传图片，拦截器放行");
            return chain.filter(exchange);
        }

        //获取token
        String token="";
        String refreshToken="";
        if (uri.startsWith("/center")&&request.getQueryParams().getFirst("token")!=null) {
         token= request.getQueryParams().getFirst("token");
          refreshToken=  request.getQueryParams().getFirst("refreshToken");
        }else{
            HttpHeaders headers = request.getHeaders();
            token = headers.getFirst("token");
            refreshToken = headers.getFirst("refreshToken");
        }


        //System.out.println("token:" + token);
        System.out.println("refreshtoken : "+refreshToken);
        //拦截信息
        JSONObject message = new JSONObject();
        message.put("status", -1);
        message.put("data", "请登录");
        byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        //refreshToken空跳转
        if (refreshToken == null || refreshToken.equals("") || redisUtil.hmget(refreshToken).size() == 0) {
            System.out.println("refreshToken条件不满足跳转");
            return response.writeWith(Mono.just(buffer));
        }
        //token空验证
        if (token == null || token.equals("")) {
            System.out.println("token空跳转");
            return response.writeWith(Mono.just(buffer));
        }

        //无效和过期判定
        try {
            JWTUtils.verify(token);
            System.out.println("token合法");
            //合法正常放行
            return chain.filter(exchange);
        } catch (TokenExpiredException e1) {
            //过期，刷新token
            System.out.println("token过期");
           /* String createToken = JWTUtils.createToken(JWTUtils.getUserId(token));
            //修改redis值
            Map<String,Object>map=new HashMap<>();
            map.put("userId",JWTUtils.getUserId(token));
            map.put("token",createToken);
            redisUtil.hmset(refreshToken,map);
            //返回客户通请求头
            //response.setHeader("token", createToken);*/
            return chain.filter(exchange);
        } catch (Exception e2) {
            //不合法
            System.out.println("token非法");
            return response.writeWith(Mono.just(buffer));
        }
    }

    @Override
    public int getOrder() {

        return 0;
    }
}
